package com.lepu.app.fun.index.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.PopUtil;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.CircularImageView;
import com.eyzhs.app.R;
import com.lepu.app.fun.index.bean.BeanWriterComment;
import com.lepu.app.fun.my.ReportActivity;

@SuppressLint({ "InflateParams", "UseSparseArrays" })
public class IndexWriterCommentAdapter extends BaseAdapter implements AsyncRequest{

	private LayoutInflater layoutInflater = null;
	private Context context = null;
	
	public ArrayList<BeanWriterComment> arrayList = null;
	
	public TextView mPraiseText = null; //记录点赞数量
	private BeanWriterComment mBean = null; //评论
	
	private String REQUEST_PRAISE = "request_praise";
	private String REQUEST_REPLY = "request_reply";
	private static final int MSG_PRAISE_SUCESS = 11;
	private static final int MSG_PRAISE_FAIL = 12;
	private static final int MSG_REPLY_SUCESS = 13;
	private static final int MSG_REPLY_FAIL = 14;
	
	private int mHotCount;
	private String mArticleId;

	public IndexWriterCommentAdapter(Context context, ArrayList<BeanWriterComment> list, String ArticleID,int hotCount) {
		this.context = context;
		layoutInflater = LayoutInflater.from(context);
		arrayList = list;
		mArticleId = ArticleID;
		mHotCount = hotCount;
	}

	@Override
	public int getCount() {
		int size = 0;
		if (arrayList != null && arrayList.size() > 0)
			size = arrayList.size();
		return size;
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (arrayList == null || arrayList.size() == 0)
			return null;
		final ViewHolder holder;

		if (convertView == null) {
			convertView = layoutInflater.inflate(R.layout.writer_comment_listview_item, null);

			holder = new ViewHolder();
			
			holder.commentLayout = (LinearLayout) convertView.findViewById(R.id.comment_layout);
			holder.replyLayout = (LinearLayout) convertView.findViewById(R.id.replyLayout);
			holder.commentTitle = (TextView) convertView.findViewById(R.id.commentTitle);
			holder.commentHeart = (CircularImageView) convertView.findViewById(R.id.commentHeart);
			holder.commentName = (TextView) convertView.findViewById(R.id.commentName);
			holder.commentTime = (TextView) convertView.findViewById(R.id.commentTime);
			holder.commentFavor = (TextView) convertView.findViewById(R.id.commentFavor);
			holder.commentContent = (TextView) convertView.findViewById(R.id.commentContent);
			holder.replyName = (TextView) convertView.findViewById(R.id.replyName);
			holder.replyTime = (TextView) convertView.findViewById(R.id.replyTime);
			holder.replyContent = (TextView) convertView.findViewById(R.id.replyContent);
			holder.replyText = (TextView) convertView.findViewById(R.id.commentReply);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
        
		//title
		if(position == 0){
			holder.commentTitle.setVisibility(View.VISIBLE);
			holder.commentTitle.setText("最热评论");
		}else if(position == mHotCount){
			holder.commentTitle.setVisibility(View.VISIBLE);
			holder.commentTitle.setText("最新评论");
		}else{
			holder.commentTitle.setVisibility(View.GONE);
		}
		
		BeanWriterComment item = arrayList.get(position);
		UniversalImageLoadTool.disPlay(item.UserAvatar, holder.commentHeart, R.drawable.app_ic_default_avatar_64);
		holder.commentName.setText(item.UserNickName);
		holder.commentTime.setText(DateUtil.getHMTime(item.RecordCreateTime));
		holder.commentFavor.setText(item.FavourCount);
		holder.commentContent.setText(item.CommentContent);

		//是否点过赞
		if(Integer.valueOf(item.HasFavour) == 0){
			holder.commentFavor.setSelected(false);
		}else{
			holder.commentFavor.setSelected(true);
		}
		
		//reply
		if(item.QuoteComment != null && !TextUtils.isEmpty(item.QuoteComment.CommentContent)){
			holder.replyLayout.setVisibility(View.VISIBLE);
			holder.replyName.setText(item.QuoteComment.UserNickName);
			holder.replyTime.setText(item.QuoteComment.RecordCreateTime);
			holder.replyContent.setText(item.QuoteComment.CommentContent);
			
		}else{
			holder.replyLayout.setVisibility(View.GONE);
		}
		
		
		holder.commentLayout.setOnClickListener(new ViewOnclicklistener(item));
		holder.commentFavor.setOnClickListener(new ViewOnclicklistener(item, holder.commentFavor));
		holder.replyText.setOnClickListener(new ViewOnclicklistener(item));
		
		return convertView;
	}
	
	
	class ViewOnclicklistener implements View.OnClickListener {
		private BeanWriterComment bean;
		private TextView textView;
		private EditText editText;
		public ViewOnclicklistener(BeanWriterComment bean, TextView textView){
			this.bean = bean;
			this.textView = textView;
		}
		public ViewOnclicklistener(EditText editText){
			this.editText = editText;
		}
		
        public ViewOnclicklistener(BeanWriterComment bean){
        	this.bean = bean;
		}
        public ViewOnclicklistener(){
		}
		@Override
		public void onClick(final View v) {
			int rid = v.getId();
			switch (rid) {
//			case R.id.commentHeart:
//				if(hospitalComment.commentUserId.equals(LoginUtil.getUserId())){
//					if(LoginUtil.jumpLogin((BaseFragmentActivity)context)){
//						return;
//					}
//					Intent intent = new Intent(context, MyUserInfoActivity.class);
//					((HospitalDetailActivity)context).startActivity(intent,true);
//				}else{
//					if(LoginUtil.jumpLogin((BaseFragmentActivity)context)){
//						return;
//					}
//					Intent intent = new Intent(context, PersonMeterialActivity.class);
//					intent.putExtra(Const.TOJID, hospitalComment.commentUserId);
//					((HospitalDetailActivity)context).startActivity(intent,true);
//				}
//				break;
			//点赞/取消点赞
			case R.id.commentFavor:
				if(LoginUtil.jumpLogin((BaseFragmentActivity)context)){
					return;
				}
				mBean = bean;
				mPraiseText = textView;
				if(mPraiseText.isSelected()){
					requestPraise(bean,0);
				}else{
					requestPraise(bean,1);
				}
				break;
			
			//list item	
			case R.id.comment_layout:
				mBean = bean;
				
				if(LoginUtil.jumpLogin((BaseFragmentActivity)context)){
					return;
				}
				showPopReport();
				break;
			case R.id.commentReply:
				mBean = bean;
				
				if(LoginUtil.jumpLogin((BaseFragmentActivity)context)){
					return;
				}
				showPopSend();
				break;
		    //回复发送
			case R.id.sendText:
				if(TextUtils.isEmpty(editText.getText().toString())){
					UIHelper.showToast(context, "请输入回复内容");
					return;
				}
				if(editText.getText().toString().length() > 500){
					UIHelper.showToast(context, "请输入500字以内回复内容");
					return;
				}
				requestReply(editText.getText().toString());
				break;
				
			case R.id.mother_detail_report: //举报
                boolean flagLoginReport = LoginUtil.jumpLogin((BaseFragmentActivity)context);
				
				if(flagLoginReport){
					return;
				}
				
				Intent intent = new Intent((BaseFragmentActivity)context, ReportActivity.class);
				intent.putExtra("reportType", 2);  //1 代表论坛主贴  2代表论坛评论
	            intent.putExtra("reportID", mBean.CommentID);
	            intent.putExtra("reportName", mBean.CommentContent);
	            ((BaseFragmentActivity)context).startActivity(intent,true);
				
				
	            PopUtil.getInstance().dismissPopWindow();
				break;
			case R.id.mother_detail_cannel: 
				PopUtil.getInstance().dismissPopWindow();
				break;
				
			default:
				break;
			}
		}
	}
	
	//显示回复布局
	public void showPopSend() {
		View view = LayoutInflater.from(context).inflate(R.layout.writer_comment_send_view, null);
		TextView sendText = (TextView) view.findViewById(R.id.sendText);
		EditText sendContent = (EditText) view.findViewById(R.id.sendEdit);
		//sendContent.setFilters(new InputFilter[] { new EmojiFilter() });
		sendText.setOnClickListener(new ViewOnclicklistener(sendContent));
		
		PopUtil.getInstance().showPopWindow((BaseFragmentActivity)context, null, view,Gravity.BOTTOM, null, true);
	}
	
	//妈妈圈举报
	@SuppressLint("InflateParams")
	public void showPopReport() {
		View view = LayoutInflater.from(context).inflate(R.layout.mother_detail_more_view2, null);
		TextView repotText = (TextView) view.findViewById(R.id.mother_detail_report);
		TextView cannelText = (TextView) view.findViewById(R.id.mother_detail_cannel);
		
		cannelText.setOnClickListener(new ViewOnclicklistener());
		
		if(mBean.UserID.equals(LoginUtil.getUserId())){
			repotText.setText("举报");
			repotText.setOnClickListener(new ViewOnclicklistener());
		}else {
			repotText.setText("举报");
			repotText.setOnClickListener(new ViewOnclicklistener());
		}
		
		PopUtil.getInstance().showPopWindow((BaseFragmentActivity)context, null, view,Gravity.BOTTOM, null, true);
	}
	
	//点赞/取消赞
	public void requestPraise(BeanWriterComment bean, int praise) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("OperationType", praise);//1点赞,0代表取消点赞
			params.put("CommentID", bean.CommentID);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getWriterCommetnFavorUrl(), map, null, this,REQUEST_PRAISE, true, false);
	}
	
	//回复
	public void requestReply(String sendContent) {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("ArticleID", mArticleId);
			params.put("QuoteCommentID", mBean.CommentID);
			params.put("CommentContent", sendContent);
			
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getWriterCommetnReplyUrl(), map, null, this,REQUEST_REPLY, true,false);
	}
	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_PRAISE_SUCESS:
				//更新点赞按钮
				if(mPraiseText.isSelected()){
					mPraiseText.setSelected(false);
					mBean.HasFavour = "0";
					mBean.FavourCount = String.valueOf(Integer.valueOf(mBean.FavourCount)-1);
					mPraiseText.setText(mBean.FavourCount);
					UIHelper.showToast(context, "取消点赞");
				}else{
					mPraiseText.setSelected(true);
					mBean.HasFavour = "1";
					mBean.FavourCount = String.valueOf(Integer.valueOf(mBean.FavourCount)+1);
					mPraiseText.setText(mBean.FavourCount);
					UIHelper.showToast(context, "点赞成功");
				}
				break;

			case MSG_REPLY_SUCESS:
				ObserverManager.getInstance().notify(ObserverConst.NOTIFY_WRITER_COMMENT_CHANGE, null, null);
				ObserverManager.getInstance().notify(ObserverConst.NOTIFY_WRITER_COMMENT_CHANGE_INFO, null, null);
				PopUtil.getInstance().dismissPopWindow();
				break;
			case MSG_PRAISE_FAIL:
				
				break;
	        case MSG_REPLY_FAIL:
				
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if(object.equals(REQUEST_PRAISE)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_PRAISE_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_REPLY)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_REPLY_SUCESS;
			msg.obj = (String) data;
			mHandler.sendMessage(msg);
		}

	}

	@Override
	public void RequestError(Object object, int arg1, String arg2) {
		if(object.equals(REQUEST_PRAISE)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_PRAISE_FAIL;
			mHandler.sendMessage(msg);
		}else if(object.equals(REQUEST_REPLY)){
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_REPLY_FAIL;
			mHandler.sendMessage(msg);
		}
	}
	
	static class ViewHolder {
		LinearLayout commentLayout,replyLayout;
		CircularImageView commentHeart;
		TextView commentTitle,commentName,commentTime,commentFavor,commentContent;
		TextView replyName,replyTime,replyContent,replyText;
	}
}
